import React, { Component } from "react";
import { Button, Form, Input, Checkbox, Switch, Spin, Radio } from "antd";
import { messages } from "share/common";
import { connect } from "react-redux";
import Priority from "components/template/priority";
import "styles/supplier-management/new-consumer-management/edit-frams/edit-frame.scss";
import NewConsumerServer from "../new-consumer-server";
import { message } from "antd/lib/index";
import ConsumerUtil from "../consumer-util";

const FormItem = Form.Item;
const Group = Checkbox.Group;
const RadioGroup = Radio.Group;

@Form.create()
class AmexEditFrame extends Component {
  constructor(props) {
    super(props);
    this.isLock = false;
    this.openTypeOptions = [
      { label: messages("supplier-1.key80") /*机票*/, value: "withFlightSupplier" },
      // { label: messages("supplier-1.key81") /*酒店*/, value: "withHotelSupplier" },
    ];
    this.approvalOptions = [
      { label: messages("supplier-1.key80") /*机票*/, value: "withFlightApproval" },
      // { label: messages("supplier-1.key81") /*酒店*/, value: "withHotelApproval" },
    ];
    this.keyName = ["openType", "openPC", "openPCOrder", "openApproval"];
    this.state = {
      editData: {},
      loading: false,
      isNew: false,
      priDefalultValue: {},
    };
  }

  componentWillMount() {
    const { params, tenant } = this.props;
    const initValue = ConsumerUtil.initPriorityData(this.props);
    if (params.companyInfos) {
      initValue.distribution = {
        companies: params.companyInfos ? params.companyInfos : [],
      };
    }
    this.setState(
      {
        editData: params,
        isNew: params.levelCode ? false : true,
        priDefalultValue: initValue,
      },
      this.props.form.resetFields
    );
  }

  onPriorityChange = (values) => {
    this.setState({
      priDefalultValue: values,
    });
  };

  onCancelEdit = () => {
    this.props.close();
    this.props.form.resetFields();
  };

  onSubmitEdit = () => {
    if (this.isLock) {
      return;
    }
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { priDefalultValue, isNew, editData } = this.state;
        const authData = JSON.parse(JSON.stringify(priDefalultValue));
        const { tenant } = this.props;
        if (!authData) {
          message.error(messages("supplier-1.key185") /*请填写所属组织*/);
          return;
        }
        if (!authData.distribution && authData.levelCode != "COMPANY") {
          message.error(messages("supplier-1.key186") /*启用公司不支持通用*/);
          return;
        }
        if (authData.levelCode != "COMPANY" && authData.distribution.companies.length <= 0) {
          message.error(messages("supplier-1.key187") /*请填写公司*/);
          return;
        }
        // const companies = { companies: [] };
        // if (authData.distribution) {
        //   authData.distribution.companies.forEach((item) => {
        //     companies.companies.push(item.companyOID);
        //   });
        //   delete authData.distribution;
        // }
        let upParams = Object.assign({}, values, authData);

        const setApprovalOptions = (enable) =>
          this.approvalOptions
            .map((item) => item.value)
            .map((item) => {
              upParams[item] = enable.includes(item);
            });
        // upParams.corpStatus = upParams.enabled ? "NORMAL" : "INVALID";
        upParams.tenantId = tenant.id;
        upParams.tenantName = tenant.tenantName;
        upParams.publicUsage = true;
        upParams.withHotelSupplier = false;
        upParams.withHotelApproval = false;

        this.openTypeOptions.map((item) => item.value).map((item) => (upParams[item] = false));
        upParams.openType.forEach((item) => {
          upParams[item] = true;
        });
        setApprovalOptions(upParams.approvalEnabled);
        delete upParams.approvalEnabled;

        if (!isNew) {
          upParams = Object.assign({ id: editData.id }, upParams);
        }
        delete upParams.openType;

        this.isLock = true;
        NewConsumerServer(this)
          .submitAmexEditData(upParams)
          .then((res) => {
            this.isLock = false;
            if (!res.data.passFlag && res.data.message) {
              message.error(res.data.message);
            } else {
              this.props.close(true);
            }
          });
      }
    });
  };

  isOpenServer = (value) => {
    if (!value) {
      // todo
    }
  };

  render() {
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const { editData, loading, isNew, priDefalultValue } = this.state;
    const formLayout = {
      labelCol: { span: 6, offset: 1 },
      wrapperCol: { span: 14 },
    };

    const initialOpenType = [];
    this.openTypeOptions.forEach(({ value }) => {
      if (editData[value]) {
        initialOpenType.push(value);
      }
    });

    const initialApproval = [];
    this.approvalOptions.forEach(({ value }) => {
      if (editData[value]) {
        initialApproval.push(value);
      }
    });

    return (
      <div className="edit-frame">
        <Spin spinning={loading}>
          <Form className="new-form">
            <FormItem label={messages("common.column.status") /*状态*/} {...formLayout}>
              {getFieldDecorator("enabled", {
                initialValue: editData.enabled || false,
                valuePropName: "checked",
              })(<Switch onChange={this.isOpenServer} />)}
            </FormItem>
            <Priority
              top="COMPANY"
              formItemLayout={formLayout}
              disabledTop={!isNew}
              companyProps={{ disabled: !isNew, valueKey: "id" }}
              defaultValue={isNew ? null : priDefalultValue}
              onChange={this.onPriorityChange}
            />
            <h3 style={{ borderBottom: 0 }}>
              <div className="other-rule-edit-title">{messages("supplier-1.key189") /*服务商参数设置*/}</div>
            </h3>
            <FormItem label={messages("supplier-1.key898") /*companyID*/} /*companyID*/ {...formLayout}>
              {getFieldDecorator("companyId", {
                initialValue: editData.companyId || "",
                rules: [
                  {
                    required: true,
                    message: messages("supplier-1.key193") /*必填*/,
                  },
                ],
              })(<Input />)}
            </FormItem>
            <FormItem label={messages("supplier-1.key899") /*partnerID*/} /*partnerID*/ {...formLayout}>
              {getFieldDecorator("partnerId", {
                initialValue: editData.partnerId || "",
                rules: [
                  {
                    required: true,
                    message: messages("supplier-1.key193") /*必填*/,
                  },
                ],
              })(<Input />)}
            </FormItem>
            <FormItem label={messages("supplier-1.key900") /*accountID*/} /*accountID*/ {...formLayout}>
              {getFieldDecorator("accountId", {
                initialValue: editData.accountId || "",
                rules: [
                  {
                    required: true,
                    message: messages("supplier-1.key193") /*必填*/,
                  },
                ],
              })(<Input />)}
            </FormItem>
            <FormItem label={messages("supplier-1.key901") /*password*/} /*password*/ {...formLayout}>
              {getFieldDecorator("passWord", {
                initialValue: editData.passWord || "",
                rules: [
                  {
                    required: true,
                    message: messages("supplier-1.key193") /*必填*/,
                  },
                ],
              })(<Input />)}
            </FormItem>
            <FormItem label={messages("supplier-1.key902") /*webPassword*/} /*webPassword*/ {...formLayout}>
              {getFieldDecorator("webPassWord", {
                initialValue: editData.webPassWord || "",
                rules: [
                  {
                    required: true,
                    message: messages("supplier-1.key193") /*必填*/,
                  },
                ],
              })(<Input />)}
            </FormItem>
            <FormItem label={messages("supplier-1.key903") /*publishEmail*/} /*publishEmail*/ {...formLayout}>
              {getFieldDecorator("publishEmail", {
                initialValue: editData.publishEmail || "",
                rules: [
                  {
                    required: true,
                    message: messages("supplier-1.key193") /*必填*/,
                  },
                ],
              })(<Input />)}
            </FormItem>
            <FormItem label={messages("supplier-1.key904") /*corpID*/} /*corpID*/ {...formLayout}>
              {getFieldDecorator("corpId", {
                initialValue: editData.corpId || "",
              })(<Input />)}
            </FormItem>
            <FormItem label={messages("supplier-1.key905") /*corpSecret*/} /*corpSecret*/ {...formLayout}>
              {getFieldDecorator("corpSecret", {
                initialValue: editData.corpSecret || "",
              })(<Input />)}
            </FormItem>
            <FormItem label={messages("supplier-1.key168") /*授权方式*/} /*授权方式*/ {...formLayout}>
              {getFieldDecorator("permissionType", {
                initialValue: editData.permissionType || 1,
              })(
                <RadioGroup>
                  <Radio value={1}>
                    {messages("supplier-1.key906") /*事前审批（先审批后预定）*/ /*事前审批（先审批后预定）*/}
                  </Radio>
                  <Radio value={2}>
                    {messages("supplier-1.key907") /*事后审批（先预定后审批）*/ /*事后审批（先预定后审批）*/}
                  </Radio>
                </RadioGroup>
              )}
            </FormItem>
            <h3 style={{ borderBottom: 0 }}>
              <div className="other-rule-edit-title">{messages("supplier-1.key194") /*服务商应用类型设置*/}</div>
            </h3>
            <FormItem
              style={{ display: "flex", alignItems: "center" }}
              label={messages("supplier-1.key195") /*应用类型*/}
              {...formLayout}
            >
              {getFieldDecorator("openType", {
                initialValue: initialOpenType || [],
              })(<Group options={this.openTypeOptions} />)}
            </FormItem>
            <h3 style={{ borderBottom: 0 }}>
              <div className="other-rule-edit-title">{messages("supplier-1.key196") /*申请单相关设置*/}</div>
            </h3>
            <FormItem
              className="form-label-style"
              label={messages("supplier-1.key197") /*行程上可选该服务商*/}
              {...formLayout}
            >
              {getFieldDecorator("approvalEnabled", {
                initialValue: initialApproval || [],
              })(<Group options={this.approvalOptions} />)}
            </FormItem>

            <h3 style={{ borderBottom: 0 }}>
              <div className="other-rule-edit-title">{messages("supplier-1.key223") /*消费商账期*/ /*消费商账期*/}</div>
            </h3>
            <div className="ant-form-item-label">结算周期：T+3</div>
          </Form>
        </Spin>
        <br />
        <br />
        <br />
        <br />
        <div className="affix-bottom">
          <Button type="primary" loading={loading} onClick={this.onSubmitEdit}>
            {messages("common.ok") /*确定*/}
          </Button>
          &nbsp;&nbsp;&nbsp;&nbsp;
          <Button onClick={this.onCancelEdit}>{messages("common.cancel") /*取消*/}</Button>
        </div>
      </div>
    );
  }
}

AmexEditFrame.getEditData = (record, data, index) => {
  const params = JSON.parse(JSON.stringify(record));
  return params;
};

function mapStateToProps(state) {
  return {
    tenant: state.login.tenant,
  };
}

export default connect(mapStateToProps)(AmexEditFrame);
